from flask import Blueprint, redirect, url_for, flash, render_template, send_from_directory, current_app, request
from flask_login import current_user, login_required
from sqlalchemy.sql.expression import func

from app.models import *
from app.forms import SuggestForm
from app.extensions import db

poly_bp = Blueprint('poly', __name__)


@poly_bp.route('/')
def index():
    subscribes = Crawler.query.order_by(func.random()).limit(6)
    return render_template('index/index.html', subscribes=subscribes)


@poly_bp.route('/suggest', methods=['GET', 'POST'])
def suggestion():
    form = SuggestForm()
    if form.validate_on_submit():
        website = form.website.data
        suggested = Suggestion.query.filter_by(website=website).first()
        if suggested:
            suggested.count += 1
            flash('感谢建议，我们会尽快添加！')
            return redirect(url_for('poly.wish_list'))
        email = form.email.data
        if current_user.is_authenticated:
            email = current_user.email
        describe = form.describe.data
        new = Suggestion(website=website, describe=describe, email=email)
        db.session.add(new)
        db.session.commit()
        flash('感谢建议，我们会尽快添加！')
        return redirect(url_for('poly.wish_list'))
    return render_template('index/suggestion.html', form=form)


@poly_bp.route('/bucket')
def wish_list():
    items = Suggestion.query.order_by(Suggestion.timestamp.desc()).all()
    return render_template('index/wishlist.html', items=items)


# 订阅商城
@poly_bp.route('/market')
@login_required
def market():
    category_id = request.args.get('category', 1, type=int)
    categories = Category.query.all()
    items = Crawler.query.filter_by(category_id=category_id)
    return render_template('index/market.html', categories=categories, items=items)


@poly_bp.route('/detail/<int:crawler_id>')
def detail(crawler_id):
    crawler = Crawler.query.get_or_404(crawler_id)
    page = request.args.get('page', 1, type=int)
    pagination = Record.query.filter_by(crawler_id=crawler_id).order_by(Record.timestamp.desc()).\
        paginate(page, per_page=20)
    records = pagination.items
    likely = Crawler.query.filter(Crawler.slug == crawler.slug, Crawler.id != crawler.id)
    if likely.count() == 0:
        likely = Crawler.query.filter(Crawler.id != crawler.id).order_by(func.random()).limit(5)
    return render_template('index/detail.html', crawler=crawler, records=records, pagination=pagination, likely=likely)


@poly_bp.route('/about')
def about():
    return render_template('index/about.html')


@poly_bp.route('/tutorial')
def tutorial():
    return render_template('index/tutorial.html')


@poly_bp.route('/covers/<path:filename>')
def get_cover(filename):
    return send_from_directory(current_app.config['CRAWLER_PIC'], filename)
